package com.bds.btcdc.adapter.zb;

import java.net.URI;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.bds.btcdc.util.EhcacheUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.handler.StompSessionHandler;
import com.bds.btcdc.model.CoinPairExchanges;
import com.bds.btcdc.model.MarketData;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.service.CoinPairExchangesService;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.SpringContextHolder;

/**
 * Created by DongChenchen on 2018/4/9 0009 ZB的WebSocket客戶端，接受ZB的行情更新推送
 */
public class ZBMarketReceiver extends WebSocketClient {
	private Logger log = LoggerFactory.getLogger(getClass());
	private final static DecimalFormat df = new DecimalFormat("#0.0000");
	private StompSession session;
	private List<CoinPairExchanges> zb_pairs;
	private CoinPairExchangesService exchangesService;

	public ZBMarketReceiver(StompSession session, URI serverURI, List<CoinPairExchanges> zb_pairs) {
		super(serverURI);
		this.session = session;
		this.zb_pairs = zb_pairs;
		this.exchangesService = SpringContextHolder.getBean(CoinPairExchangesService.class);

	}

	public ZBMarketReceiver(URI serverUri, Draft draft) {
		super(serverUri, draft);
	}

	public ZBMarketReceiver(URI serverURI) {
		super(serverURI);
	}

	@Override
	public void onOpen(ServerHandshake handshakedata) {
		for (CoinPairExchanges pair_exchanges : zb_pairs) {
			String dataMsg = "{'event':'addChannel','channel':'" + pair_exchanges.getPair_code() + "_ticker'}";
			send(dataMsg);
		}
		log.info("######### ZB 获取行情 连接成功 #############");
	}

	@Override
	public void onClose(int code, String reason, boolean remote) {
		log.info("ZB 连接关闭,code： " + code + " 异常信息：" + reason);
//		if (code == -1) {
			new Thread() {
				@Override
				public void run() {
					try {
						Thread.sleep(Const.RE_CONN_TIME);
						log.info("ZB 重新建立连接........");
						new ZBMarketReceiver(session, new URI(Const.ZB.WS_URL), zb_pairs).connect();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
		}
//	}

	/**
	 * @param message
	 *            { "channel": "ltcbtc_ticker",当前请求的channel "date":
	 *            "1472800466093",返回数据时服务器时间 "no": 245539, "ticker": { "buy":
	 *            "3826.94",买一价 "high": "3838.22",最高价 "last": "3826.94",最新成交价
	 *            "low": "3802.0",最低价 "sell": "3828.25",卖一价 "vol":
	 *            "90151.83"成交量(最近的24小时) }
	 */
	@Override
	public synchronized void onMessage(String message) {
		try{
//			log.info("ZB行情更新..." );
			Result ret = new Result();
			List<MarketData> ms = new ArrayList<MarketData>();
			MarketData data = new MarketData();
			JSONObject msg = JSONObject.parseObject(message);
			String tickerStr = msg.getString("ticker");
			JSONObject ticker = JSONObject.parseObject(tickerStr);
			String date = msg.getString("date");
			if (date != null) {
				data.setTimestamp(Long.parseLong(date));
				data.setExchange(Const.ZB.EXCHANGE);
				data.setBuy(ticker.getString("buy"));
				data.setSell(ticker.getString("sell"));
				data.setHigh(ticker.getString("high"));
				data.setLow(ticker.getString("low"));
				data.setLast(ticker.getString("last"));
				data.setVol(df.format(ticker.getBigDecimal("vol")));
				String pair = msg.getString("channel").split("_")[0];//ltcbtc_ticker
				String btc_pair = exchangesService.getBtcPair(Const.ZB.EXCHANGE, pair);
				data.setPair(btc_pair);
				try {
					//usdt 币对的最新交易价格存到缓存（资产情况统计）
					if (btc_pair.toUpperCase().contains("USDT")
							|| btc_pair.toUpperCase().contains("USD")) {
						EhcacheUtils.getInstance().putCache(Const.ZB.EXCHANGE + "#" + btc_pair.toUpperCase(),ticker.getString("last"));
					}
				}catch (Exception e){
					log.info("ZB  usdt 币对的最新交易价格存到缓存 失败");
				}
				ms.add(data);
				ret.setCode(Const.SUC);
				ret.setData(ms);
				if (session != null) {
					// 推到btc-web主题
					synchronized (session) {
						session.send(Const.ZB.MARKET_TOPIC, JSONObject.toJSONString(ret).getBytes());
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void onMessage(ByteBuffer message) {
		log.info("received ByteBuffer");
	}

	@Override
	public void onError(Exception ex) {
		log.info("an error occurred:" + ex);
	}

	// 测试Receiver
	public static void main(String[] args) throws Exception {

		org.springframework.web.socket.client.WebSocketClient client = new StandardWebSocketClient();

		WebSocketStompClient stompClient = new WebSocketStompClient(client);
		stompClient.setMessageConverter(new MappingJackson2MessageConverter());

		StompSessionHandler sessionHandler = new StompSessionHandler();
		// ws://localhost:8088/market_info：btc-web发布的websocket服务
		stompClient.connect("wss://api.zb.com:9999/websocket", sessionHandler);
	}
}